#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>



int sh1(char *command){
  int argc = 0;
  char* argv[16] = {NULL};
  char *str = (char*)malloc(sizeof(command));
  strcpy(str,command);
  argv[argc] = strtok(str," \n");
  while(argv[argc] != NULL){
    argc++;
    argv[argc] = strtok(NULL," \n");
  }
  if(strcmp(argv[0], "cd") == 0 || strcmp(argv[0], "pwd") == 0 || strcmp(argv[0], "exit") == 0) {
    if(strcmp(argv[0], "cd") == 0){
      //printf("-------command is cd--------\n");
      int error = chdir(argv[1]);
      if(error < 0) 
        perror("cd");
      else {
        char *path = getcwd(NULL, 0);
        printf("%s\n", path);
        free(path);
      }
    }
    else if(strcmp(argv[0], "pwd") == 0) {
      //printf("-------command is pwd--------\n");
      char *path = getcwd(NULL, 0);
      printf("%s\n", path);
      free(path);
    }
    else if(strcmp(argv[0], "exit") == 0) {
      //printf("-------command is exit--------\n");
      exit(0);
    }
    return 0;
  }
  pid_t pid;
  pid = fork();
  if(pid == 0) {
    int error = execvp(argv[0], argv);
    if(error < 0) perror("execvp");
  }
  wait(NULL);
}

int main() {
  char command[32];
  int count;
  while(1) {
    write(1, ">", sizeof(">"));
    count = read(0, command, sizeof(command));
    command[count] = 0;
    sh1(command);
  }
  return 0;
}
